package org.Java2D;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

import javax.swing.JComponent;

import pasantias.Dominio.BoardRender;
import pasantias.Dominio.Circle;
import pasantias.Dominio.Dot;
import pasantias.Dominio.Figura;
import pasantias.Dominio.FiguresVisitor;
import pasantias.Dominio.InmutableBoard;
import pasantias.Dominio.Rectangle;
import pasantias.Dominio.Square;

public class Canvas extends JComponent implements BoardRender {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private InmutableBoard board;
	private FiguresVisitor figuresVisitor;

	public Canvas() {
		this.setBackground(Color.white);
	}

	@Override
	public void paintComponent(final Graphics graphics) {
		RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
		((Graphics2D) graphics).setRenderingHints(renderingHints);

		figuresVisitor = new FiguresVisitor() {

			@Override
			public void visit(Square square) {
				int height = square.getHeight() * 10;
				int width = square.getWidth() * 10;
				Dot vertex = square.getVertex();
				graphics.setColor(Color.yellow);
				graphics.fillRect(vertex.getX() * 10, vertex.getY() * 10, width, height);
			}

			@Override
			public void visit(Rectangle rectangle) {
				int height = rectangle.getHeight() * 10;
				int width = rectangle.getWidth() * 10;
				Dot vertex = rectangle.getVertex();
				graphics.setColor(Color.blue);
				graphics.fillRect(vertex.getX() * 10, vertex.getY() * 10, width, height);
			}

			@Override
			public void visit(Dot dot) {
				graphics.setColor(Color.red);
				graphics.fillOval(dot.getX() * 10, dot.getY() * 10, 5, 5);
			}

			@Override
			public void visit(Circle circle) {
				int radius = circle.getRadius() * 10;
				Dot center = circle.getCenter();
				graphics.setColor(Color.green);
				graphics.fillOval(center.getX() * 10, center.getY() * 10, radius, radius);
			}
		};


		
		for (Figura figura : board.getFigures()) {
			figura.accept(figuresVisitor);
		}
	}

	@Override
	public Dimension getPreferredSize() {
		return new Dimension(board.getWidth() * 10, board.getHeigh() * 10);
	}

	@Override
	public Dimension getMinimumSize() {
		return getPreferredSize();
	}

	@Override
	public void draw(InmutableBoard boardInmutable) {
		this.board = boardInmutable;

	}

	public BufferedImage toImage() {
		BufferedImage image = new BufferedImage(400,400,BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics2d = image.createGraphics();
		this.paintComponent(graphics2d);
		return image;
	}

}